package dhee.wtqshopproject.utils;


import dhee.wtqshopproject.dao.CategoryMapper;
import dhee.wtqshopproject.dao.ProductMapper;
import dhee.wtqshopproject.entity.Admin;
import dhee.wtqshopproject.entity.Category;
import dhee.wtqshopproject.entity.Product;
import dhee.wtqshopproject.entity.User;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
public class ProductUtils {

    private static ProductUtils productUtils;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @PostConstruct
    public void init() {
        productUtils = this;
        productUtils.productMapper = this.productMapper;
        productUtils.categoryMapper = this.categoryMapper;
    }

    // 通用权限校验方法
    private static void checkAdminPermission() {
        Admin currentUser = AdminThread.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }
        if (!"admin".equals(currentUser.getRole())) {
            throw new RuntimeException("权限不足，需要管理员权限");
        }
    }

    // 校验分类是否存在
    private static void checkCategoryExist(String categoryId) {
        Category category = productUtils.categoryMapper.selectById(Integer.parseInt(categoryId));
        if (category == null || !Objects.equals(category.getIsUse(), 1)) {
            throw new RuntimeException("分类不存在或已停用");
        }
    }

    // 新增商品
    public static void insertProduct(Product product) {
        checkAdminPermission();
        checkCategoryExist(product.getCategoryId());
        productUtils.productMapper.insertProduct(product);
    }

    // 修改商品
    public static void updateProduct(Product product) {
        checkAdminPermission();
        checkCategoryExist(product.getCategoryId());
        productUtils.productMapper.updateProduct(product);
    }

    //删除
    public static void deleteProduct(Integer productId) {
        checkAdminPermission();
        productUtils.productMapper.deleteProductById(productId);
    }
  //查询
    public static List<Product> selectAllProducts() {
        return productUtils.productMapper.selectAllProducts();
    }
   //分类id查询
    public static Product selectProductById(Integer productId) {
        return productUtils.productMapper.selectProductById(productId);
    }
}